package service.user;

import dao.user.UserDao;
import dao.user.UserDaoImpl;
import domain.User;
import util.EncryptUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDaoImpl();
    /**
     * 登录验证
     * @param username
     * @param password
     * @return User
     * @author 夏添
     * @date 2020/9/17 15:58
     */
    public User verifyUser(String username, String password){
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String login_time = dateFormat.format(date);
        password = EncryptUtil.getMD5(password);
        User user = new User();
        try {
            user = userDao.verifyUser(username,password);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(user.getUser_id()!=0){
            try {
                int i = userDao.updateLoginTime(user.getUser_id(),login_time);
                if (i!=0){
                    user.setLogin_time(login_time);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return user;
    }

    /**
     * 修改密码
     * @param userId
     * @param newPassword
     * @return int
     * @author 夏添
     * @date 2020/9/17 16:09
     */
    public int updatePassword(int userId, String newPassword) {
        String pasword = EncryptUtil.getMD5(newPassword);
        int i = 0;
        try {
            i = userDao.updatePassword(userId, pasword);
        }catch (Exception e){
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 获取用户列表
     * @return List<User>
     * @author 夏添
     * @date 2020/9/23 16:03
     */
    public List<User> getUserList(){
        List<User> list = new ArrayList<>();
        try {
            list = userDao.getUserList();
        }catch (Exception e){
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 添加用户
     * @param username
     * @param name
     * @param password
     * @return int
     * @author 夏添
     * @date 2020/9/23 17:26
     */
    public int addUser(String username, String name, String password){
        password = EncryptUtil.getMD5(password);
        int i = 0;
        try {
            i = userDao.addUser(username,name,password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return i;
    }
}
